# -*- coding:utf-8 -*-
import os, sys, time, subprocess, glob, json  # ,msvcrt
import shutil
# from start import Input
from apptoolkit import Device
from appium import webdriver

# 获取配置信息
def Getconfig():
    ios_devices = Device().get_ios_devices()
    print(ios_devices)
    config = {"Pacname": "Pacname", "WMname": "WMname", "Yaml": "Yaml"}
    openfile = open("./.config_mac", mode='r')
    # 读取配置信息读行次数
    try:
        while True:
            line = openfile.readline().strip().split(":")
            if line[0] == "Pacname":
                config["Pacname"] = line[1]
                print ("AppCrawler包名:%s, 读取成功" % (config["Pacname"]))
            elif line[0] == "WMname":
                config["WMname"] = line[1]
                print("外卖App包名: %s, 读取成功" % (config["WMname"]))
            elif line[0] == "Yaml":
                config["Yaml"] = line[1]
                print("配置文件名: %s, 读取成功" % (config["Yaml"]))
            else:
                break
    except:
        print("配置文件有误, 请检查")
    finally:
        openfile.close()
        print("读取配置信息成功, 即将开始遍历")
        time.sleep(3)
        return config


# # 终端运行xcode，启动webDriverAgentRunner
def webDriverAgentRunner():
    os.system('sh webDriverAgent.sh')

# 终端运行AppCrawlerJar 包
# author: QA-limin
def Runjar():
    # 本处输入执行命令
    Command = "java -jar %s " \
              "-a " \
              "%s" \
              " -p ios" \
              " --capability platformName=iOS,automationName=XCUITest,platformVersion=11.2" \
              % (Input.get("Pacname"),  Input.get("WMname"))
    print(Command)
    os.system("cd ./appcrawler")
    os.system(Command)

# 重置手机链接，taskkill是windows下的命令，在mac中运行不成功
def reset():
    adb = "taskkill -f -t -im adb.exe"   # -t: 终止进程及其子程序 -f:强项终止进程 -im：依据文件名
    kadb = "taskkill -f -t -im kadb.exe"
    device = "adb devices"
    os.system(adb)
    os.system(kadb)
    os.system(device)


# 拷贝文件
def copyfiles(path, files):
    for i in files:
        shutil.copy(i, path)

def killAppiumProgress():
    subprocess.Popen('killall node',shell = True)
    # os.system('pkill appium')
    # appiumProgress = os.system('ps aux | grep appium')

def startappium():
    # subprocess.Popen([sys.executable, 'appium.py'], creationflags=subprocess.CREATE_NEW_CONSOLE)
    # subprocess.Popen([sys.executable, 'appium_start.py'])
    os.system("appium --session-override")

#以下代码是执行一台手机，若执行多台手机时，就要用for循环遍历设备信息
def startXCUITEST():
    all_ios_devices = Device().get_ios_devices()
    print(all_ios_devices)
    for i in range(len(all_ios_devices)):
            print(i)
            ios_devices=all_ios_devices[i]
            print(ios_devices)
            desired_caps = {}
            desired_caps['automationName'] = 'XCUITest'
            desired_caps['appium-version'] = '1.6.3'
            desired_caps['platformName'] = ios_devices['os_type']
            desired_caps['deviceType'] = ios_devices['os_type']
            # desired_caps['platformVersion'] = '11.0.1'
            desired_caps['platformVersion'] = ios_devices['rom_version']
            # desired_caps['deviceName'] = 'iPhone 6'
            desired_caps['deviceName'] = ios_devices['model']
            # desired_caps['udid'] = '5d9ee406534f4445d0ce03744916600fa1e71afa'
            desired_caps['udid'] = ios_devices['uid']
            desired_caps['bundleId'] = 'com.baidu.xiaodu.waimai'
            desired_caps['autoAcceptAlerts'] = True
            desired_caps['noReset'] = True
            print(desired_caps)
            driver = webdriver.Remote('http://0.0.0.0:4723/wd/hub', desired_caps)

# 找到目标日志文件夹
def findTargetLogFolder():
    current_path = os.getcwd()
    foldergroup = []
    platform = "ios"
    for root, dirs, files in os.walk(current_path, topdown=False):
        for folder in dirs:
            foldername = os.path.join(root, folder)
            if platform in foldername:
                foldername = foldername.split("_")
                foldername = foldername[1].split("/")
                foldername = foldername[0]
                foldergroup.append(foldername)

    result = max(foldergroup)
    for targetLogFolder in os.listdir("."):
        if result in targetLogFolder:
            targetLogFolder = os.path.join(os.getcwd(), targetLogFolder)
            # print(result)
            return targetLogFolder


# 在目标日志文件夹中过滤har文件
def logFilter():
    targetLogFolder = findTargetLogFolder()
    print("targetLogFolder" + targetLogFolder)
    currentpath = os.chdir(targetLogFolder)
    harfiles = glob.glob("*.har")
    # print(harfiles)
    return harfiles


# 错误日志筛选规则
def verifylog(json_str, harfile):
    entries = json_str['log']['entries']
    for response in entries:
        error_num = 0
        # 解释json
        status = response['response']['status']
        content = response['response']['content']
        mimeType = content['mimeType']
        try:
            if content.get('text') == None:
                pass
            elif mimeType != "application/json":
                pass
            else:
                text = content['text']
                text_json = json.loads(text)
                if 'error_no' in text_json.keys() == True:
                    error_no = text_json['error_no']
                    print("error_no为%s" % error_no)
                    if error_no == 0:
                        pass
                    elif status == 200:
                        pass
                    else:
                        error_num += 1
                        print("此日志有错误")
                else:
                    pass
        except:
            pass

    return error_num


# 执行遍历日志文件, 进行错误日志筛选
def verifylog_exe():
    harfiles = logFilter()
    for i in harfiles:
        print("当前验证日志文件:%s" % i)
        # openfile = open("./.config", encoding='UTFmode = 'r')


        with open(i, 'r', encoding='UTF-8') as w:
            json_str = json.loads(w.readline())
            error_num = verifylog(json_str, i)
    if error_num == 0:
        print("恭喜你, 没有报错日志")
    else:
        print("共有%s处错误" % error_num)

# 启动入口
# 重置手机链接
# reset()

#验证appium是否启动，若启动，杀掉所有appium的进程
# killAppiumProgress()

#
# # 启动Appium
# startappium()


# #使用脚本 运行 WebDriverAgent
# webDriverAgentRunner()
webDriverAgentRunner()

# #打开XCUITEST
startXCUITEST()

# subprocess.Popen([sys.executable, 'appium.py'],creationflags = subprocess.CREATE_NEW_CONSOLE)
# 获取配置信息
Input = Getconfig()
#
# # 运行appcrawler
Runjar()
# # 执行验证日志文件
# verifylog_exe()


# input = ("任意键结束")
